<template>
	<view>
		<!--进度条实现思路， 通过来源不同类型数据， 来决定展示的百分比-->
		<!--进度条的一个div里面嵌套一个div-->
		<view class="od-banner">
			<image  class="od-banner-icon"  mode="widthFix" src="/static/resource/images/od_bg_icon.png"/>
			<view class="od-jd od-jd-0">
				<view class="od-jd-out">
					<view class="od-jd-in"></view>
				</view>
				<view class="vp-flex od-jd-text" >
					<view class="vp-flex_1">
						<text class="od-jd-st-0">填写订单</text>
					</view>
					<view class="vp-flex_1">
							<text class="od-jd-st-10">在线支付</text>
					</view>
					<view class="vp-flex_1">
							<text class="od-jd-st-20">专人服务</text>
					</view>
					<view class="vp-flex_1">
							<text class="od-jd-st-30">服务完成</text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="pub-box">
			<view class="pub-box-bd">
			<view class="weui-cell weui-cell_input">
				<view class="weui-cell__hd">
					<image class="serv-icon" :src="service.logo_image? service.icon_image_url:'../../static/resource/images/avatar.jpg'"></image>
				</view>
				<view class="weui-cell__bd">
				  <text>{{service.name}}</text>
				</view>
				<view class="weui-cell__ft">
					<view @click="handleTap"   class="f5 ic_info">服务内容</view>
				</view>
			</view>
			</view>
		</view>
	    <!--每个服务的页面结构不一样-->
		<block v-if="service.stype==10 || service.stype == 15 ||service.stype== 20">
			<view class="pub-box">
				<view  class="pub-box-bd">
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">
								就诊医院
							</view>
						</view>
						
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
									<picker @change="onHospitalChange" :value="hospital_index" :range="hospitals" range-key="name">
										<input type="text" :disabled="true" placeholder="请选择要就诊的医院" :value="hospitals[hospital_index].name"/>
									</picker>
							</view>
						</view>
					</view>
					
					<!--就诊时间-->
					<view class="weui-cell weui-cell_input">
						<view class="weui-cell__hd">
							<view class="weui-label">
								就诊时间
							</view>
						</view>
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
						     <dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.starttime" placeholder="请选择就诊时间"></dtPicker>
							</view>
						</view>
					</view> 
					<!--就诊人-->
					<view class="weui-cell weui-cell_input" @click="onClientChange">
						<view class="weui-cell__hd">
							<view class="weui-label">
								就诊人
							</view>
						</view>
						
						<view class="weui-cell__bd"></view>
						<view class="weui-cell__ft weui-cell__ft_in-access">
							<view>
									<input class="weui-input"  placeholder-class="vp-placeholder" placeholder="请选择就诊人" style="text-align:right;" :disabled="true" :value="client.name" type="text"/>
							</view>
						</view>
					</view>
					
					<!--接送地址-->
					<block v-if="service.stype == 15">
						<view class="weui-cell weui-cell_input">
							<view class="weui-cell__hd">
							<view class="weui-label">
								接送地址
							</view>
							</view>
								<view class="weui-cell__bd">
								<input class="weui-input" name = "receiveAddress" style="text-align: right;"
								placeholder-class="vp-placeholder" placeholder="请填写就诊人所在地址"
								v-model ="order.receiveAddress">
							</view>
						</view>
						<view class="weui-cell weui-cell_input">
							<view class="weui-cell__hd">
								<view class="weui-label">
									联系电话
								</view>
							</view>
							<view class="weui-cell__bd">
								<input class="weui-input" name = "receiveAddress" style="text-align: right;"
								placeholder-class="vp-placeholder" placeholder="请填写您的联系电话"
								v-model ="order.tel">
							</view>
						</view>
				        <view class="pub-box">
							<view class="pub-box-tt">服务需求</view>
							<view class="pub-box-bd">
								<view class="weui-cell weui-cell_input" >
									<view class="weui-cell__bd">
										<textarea name="demand" auto-height placeholder="请简单描述您要就诊的科室.."
										placeholder-class="vp-placeholder" style="min-height: 150rpx" v-model="order.demand"/>
									</view>
								</view>
							</view>
						</view>
					</block>
				</view>
			</view>
		</block>
		
		  <block v-if="service.stype == 30 || service.stype == 40">
		        <!-- 送取结果,代跑取药 -->
		        <view class="pub-box">
		            <view class="pub-box-bd">
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__hd">
		                        <view class="weui-label">所在医院</view>
		                    </view>
		                    <view class="weui-cell__bd"></view>
		                    <view class="weui-cell__ft weui-cell__ft_in-access">
		                        <view>
		                            <picker @change="onHospitalChange" :value="hospital_index" :range="hospitals"
		                                range-key="name">
		                                <input type="text" :disabled="true" placeholder="请选择就诊所在医院"
		                                    :value="hospitals[hospital_index].name" placeholder-class="vp-placeholder" />
		                            </picker>
		                        </view>
		                    </view>
		                </view>
		
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__hd">
		                        <view class="weui-label">服务时间</view>
		                    </view>
		                    <view class="weui-cell__bd"></view>
		                    <view class="weui-cell__ft weui-cell__ft_in-access">
		                        <view>
		                            <dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.starttime"
		                                placeholder="请选择期望服务时间"></dtPicker>
		                        </view>
		                    </view>
		                </view>
		
		                <view class="weui-cell weui-cell_input" @click="onAddressChange">
		                    <view class="weui-cell__hd">
		                        <view class="weui-label">收件信息</view>
		                    </view>
		                    <view class="weui-cell__bd"></view>
		                    <view class="weui-cell__ft weui-cell__ft_in-access">
		                        <input class="weui-input" :disabled="true" style="text-align: right"
		                            placeholder-class="vp-placeholder" placeholder="请选择收件信息" :value="
		                                                            order.address.userName
		                                                                ? order.address.userName + '(' + order.address.cityName + order.address.countyName + order.address.detailInfo + ')'
		                                                                : ''
		                                                        " />
		                        <!-- {{order.address?(order.address.userName+'('+order.address.telNumber+')'):''}} -->
		                    </view>
		                </view>
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__hd">联系电话</view>
		                    <view class="weui-cell__bd">
		                        <input class="weui-input" type="number" name="tel" style="text-align: right"
		                            placeholder-class="vp-placeholder" placeholder="请填写您的联系电话" v-model="order.tel" />
		                    </view>
		                </view>
		            </view>
		        </view>
		
		        <view class="pub-box">
		            <view class="pub-box-tt">服务需求</view>
		            <view class="pub-box-bd">
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__bd">
		                        <textarea name="demand" auto-height placeholder="如有其他服务要求请在此填写.."
		                            placeholder-class="vp-placeholder" style="min-height: 150rpx" v-model="order.demand" />
		                    </view>
		                </view>
		            </view>
		        </view>
		    </block>
		    <block v-if="service.stype == 110">
		        <!-- 上门服务 -->
		        <view class="pub-box">
		            <view class="pub-box-bd">
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__hd">
		                        <view class="weui-label">服务时间</view>
		                    </view>
		                    <view class="weui-cell__bd"></view>
		                    <view class="weui-cell__ft weui-cell__ft_in-access">
		                        <view>
		                            <dtPicker @dtPickerChanged="onStartTimeChanged" :timestamp="order.starttime"
		                                placeholder="请选择期望服务时间"></dtPicker>
		                        </view>
		                    </view>
		                </view>
		
		                <view class="weui-cell weui-cell_input" @click="onClientChange">
		                    <view class="weui-cell__hd">服务对象</view>
		                    <view class="weui-cell__bd"></view>
		                    <view class="weui-cell__ft weui-cell__ft_in-access">
		                        <input class="weui-input" :disabled="true" style="text-align: right"
		                            placeholder-class="vp-placeholder" placeholder="请选择服务对象" :value="client.name" />
		                    </view>
		                </view>
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__hd">服务地址</view>
		                    <view class="weui-cell__bd">
		                        <input class="weui-input" name="receiveAddress" style="text-align: right"
		                            placeholder-class="vp-placeholder" placeholder="请填写服务所在地址" v-model="order.receiveAddress" />
		                    </view>
		                </view>
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__hd">联系电话</view>
		                    <view class="weui-cell__bd">
		                        <input class="weui-input" type="number" name="tel" style="text-align: right"
		                            placeholder-class="vp-placeholder" placeholder="请填写您的联系电话" v-model="order.tel" />
		                    </view>
		                </view>
		            </view>
		        </view>
		
		        <view class="pub-box">
		            <view class="pub-box-tt">服务需求</view>
		            <view class="pub-box-bd">
		                <view class="weui-cell weui-cell_input">
		                    <view class="weui-cell__bd">
		                        <textarea name="demand" auto-height placeholder="请简单描述您要就诊的科室.."
		                            placeholder-class="vp-placeholder" style="min-height: 150rpx" v-model="order.demand" />
		                    </view>
		                </view>
		            </view>
		        </view>
		    </block>
		
            <view style="height: 300rpx;"></view>
					
			<!--悬浮提交按钮 是否同意 ， 实现方式是通过取反来切换图片显示效果-->
			<view class="vp-foot">
				<view class="background: #FFF; padding: 20rpx;">
					<view class="xieyi">
						    <text :class="'is_xieyi ' + (is_xieyi ? 'is_xieyi_on' : '')" @click="onXieyiChange">我已阅读并同意</text>
						<navigator :url="cfg.page_xy">《用户协议》</navigator>
						<text>和</text>
						<navigator :url="cfg.page_fw">《服务协议》</navigator>
					</view>
				</view>
				<button :class="'btnp ' + (is_xieyi ? '' : 'btnp-disabled')" @click="submit">
					确认下单
					<block v-if="order.price > 0">（支付{{ order.price }}元）</block>
				</button>
			</view>	  
			<uni-popup ref="popup" type="center" 
			:is-mask-click = "false"
			background-color="#fff">
			 <view class="popup-content">
				 <view class="group">
				 <input class="uni-input" type="tel" v-model="validMobile.phone" placeholder="手机号" />
				 </view>
				 <view class="group">
					 <input class="uni-input" v-model="validMobile.vaildCode" placeholder="验证码"/>
					 <text class="valid-text" @click="countdownChange">{{countdown.validText}}</text>
				 </view>
				 
			 </view>
			 <view class="btns">
				 <view class="cancal" @click="">取消</view>
				 <view class="ok" @click="ok">确定</view>
			 </view>
			</uni-popup>
			
			
			<uni-popup ref="qrcodePopup" type="center"
			:is-mask-click = "false"
			background-color="#fff">
			<view class="pay-box">
				    <image @click="paymnet" src="/static/resource/images/modal_closer.png" style="display:block;width:30rpx; height: 30rpx;"></image>
					<view class="text-center">微信支付</view>
					<canvas id="qrcode" canvas-id="qrcode" style="width: 300rpx;height: 300rpx;"></canvas>
					<view class="text-center">请用本人微信扫码二维码</view>
					
			</view>
			</uni-popup>
	</view>
</template>

<script setup>
	import {reactive, ref,toRaw } from 'vue'
	import {onLoad} from '@dcloudio/uni-app'
	
	import UQRCode from 'uqrcodejs'; //生成二维码插件
	
	
	onLoad(options => {
		console.log(options,'options')
		main_load(options)
	})
	
	const app = getApp()
	//业务服务详情数据
	const service = ref({})
	//选中的医院索引
	const hospital_index = ref(0)
	
	//医院选项
	const hospitals = ref([])
	
	//选中的就诊人
	const client = ref({})
	//弹框
	const popup = ref()
	
	//二维码弹框
	const qrcodePopup = ref()
	const cfg = reactive({
		page_xy:'',
		page_fw:''
	})
	
	//是否同意协议
	const is_xieyi = ref(false)
	//校验
	const validMobile = reactive({
		phone:"",
		vaildCode:""
	})
	//倒计时
	const countdown = reactive({
		validText:"获取验证码",
		time: 60
	})
	
	//订单数据
	const order  = reactive({
		price:'',
		starttime:'',
		address:{
			userName:"",
			cityName:"",
			countyName:"",
			detailInfo:""
		}
	})
	
	const main_load = (options) => {
		app.globalData.utils.request({
			url: '/Service/order',
			data:{
				svid: options.svid
			},
			success: (res) =>{
				console.log(res)
				service.value = res.data.service
				hospitals.value = res.data.hospitals
				//默认选中功能
				//将响应数据转换为普通数据
				const hospitalsData = toRaw(hospitals)
				if(options.hid >0 ){
					for(let i=0;i<hospitalsData.length; i++){
						if(hospitalsData[i].id = options.hid){
								hospital_index.value = i
								order.price = hospitalsData[i].service_price
								break;
						}
					}
				}
			}
		})
	}
	
	//2. 点击弹出服务提醒
	const handleTap = () => {
		
	}
	
	//当我们修改医院时
	const onHospitalChange = (e) => {
		//1.获取当前选中医院的下标
		const value = parseInt(e.detail.value)
		//2. 将下标赋值给hospital_index
		hospital_index.value = value
		//3.根据下标获取当前选中医院的价格
		order.price = toRaw(hospitals.value)[value].service_price
	}
	
	//获取就诊时间
	const onStartTimeChanged = (val) => {
		order.starttime = val.detail.value
	}


   //选择就诊人
   const onClientChange = () => {
	   uni.navigateTo({
	   	url: "/pages/clients/index?act=select"
	   })
   }
   
   
   //创建监听全局的自定义事件uni。emit触发， uni.$on 来监听用于页面交互
   uni.$on('clientChange',(data)=>{
	   console.log(data,"监听就诊人信息")
	   client.value = data
	   // client.name = data.name
	   // client.id = data.id
	   // client.sex = data.sex
	   // client.age = data.age
	   // client.mobile = data.mobile
   })
   
   
   //是否同意协议
   const onXieyiChange = () => {
	   is_xieyi.value = !is_xieyi.value
   }
   
   //收件地址
   const onAddressChange = () => {
	   uni.chooseAddress({
	   	  success: (res) => {
			  order.address.userName = res.userName
			  order.address.cityName = res.cityName
			  order.address.countyName = res.countyName
			  order.address.detailInfo = res.detailInfo
	   	  },
		  fail: res => {
			  console.log(res,"error")
		  }
	   })
   }
   
   let submitOrder
   //下单
   const submit = () => {
	   if(!is_xieyi.value){
		   uni.showToast({
		   	title:"请先阅读并同意用户协议与服务协议",
			icon:"none",
			duration:1000
			
		   })
		   return
	   }
	   //注意reactive 与ref转换为普通对象的方式是不一样的， 如ref 是要.value
	   const orderData = toRaw(order)
	   const serviceData = toRaw(service.value)
	   const hospitalsData = toRaw(hospitals.value)
	   const clientData = toRaw(client.value)
	   orderData.service_code = serviceData.code
	   orderData.service_id = serviceData.id
	   orderData.service_name = serviceData.name
	   orderData.service_stype= serviceData.stype
	   //判断
	   //1.医院的选择校验
	   if(serviceData.stype< 100){
		   if(!hospitalsData[hospital_index.value].id){
			   uni.showToast({
			   	title:"请选择医院",
				icon:"none",
				duration:1000
			   })
			   return
		   }
		   orderData.hospital_id = hospitalsData[hospital_index.value].id
		   orderData.hospital_name = hospitalsData[hospital_index.value].name
	   }
	   
	   //就诊时间
	   if(!orderData.starttime) {
		   return uni.showToast({
		   	title:"请选择时间",
		   	icon:"none",
		   	duration:1000
		   })
	   }
	   
	   //若服务类型是陪诊
	   if(serviceData.stype == 10 || serviceData.stype == 15 || serviceData.stype == 20 ){
		  //校验就诊人
		  if(!clientData.id) {
		  		   return uni.showToast({
		  		   	title:"请选择就诊人",
		  		   	icon:"none",
		  		   	duration:1000
		  		   })
		  }
		  //验证下这个可以全部一一对应赋值吗
		   orderData.client = {...clientData}
		   
		   //校验接送地址
		   if(serviceData.stype == 15){
			   //针对陪诊服务接送地址校验
			   if(!orderData.receiveAddress) {
			   		   return uni.showToast({
			   		   	title:"请填写就诊人所在地址",
			   		   	icon:"none",
			   		   	duration:1000
			   		   })
			   }
		   }
	   }
	   
	   if(serviceData.stype == 30 || serviceData.stype == 40){
		   if(!orderData.address.userName) {
		   		   return uni.showToast({
		   		   	title:"请选择收件信息",
		   		   	icon:"none",
		   		   	duration:1000
		   		   })
		   }
	   }
	   
	//校验联系电话   
	if(!orderData.tel) {
			   return uni.showToast({
			   	title:"请填写您的联系电话",
			   	icon:"none",
			   	duration:1000
			   })
	}
	submitOrder = orderData
	// console.log(orderData,"orderData")
	if(!uni.getStorageSync('token')){
		//如果用户不存在则打开弹框
		popup.value.open('center')
	}else{
		//当用户存在 则直接
		createOrder(submitOrder)
	}
   }
   
   const cancel = () => {
	   popup.value.close()
   }
   const ok = () => {
	   //校验手机号和验证码
	   if(!validMobile.phone || !validMobile.vaildCode){
		   return   uni.showToast({
			  	title: "请检查填写数据",
				icon: 'none',
				duration: 1000
			  })
	   }
	   
	   //验证通过
	   //调用验证短信
	   app.globalData.utils.request({
		   url:"/user/authentication",
		   method:"POST",
		   data:{
			   tel:validMobile.phone,
			   code: validMobile.vaildCode
		   },
		   success : res => {
			   //将token进行缓存
			   uni.setStorageSync('token',res.data.token)
			   //调用下单方法
			   createOrder(submitOrder)
		   },
		   fail: res => {
			   uni.showToast({
			   	title: res.msg,
			   	icon:"none",
			   	duration:1000
			   })
		   }
	   })
   }
   let flag = false;
   const countdownChange = () => {
	   //判断手机号是否存在
	   if(!validMobile.phone){
		   return uni.showToast({
		   	title:"请输入手机号",
		   	icon:"none",
		   	duration:1000
		   })
	   }
	   
	   //填写好之后，需要做个倒计时功能
	   //当flag为true时则不让它点击
	   if(flag) return 
	   const time = setInterval(() => {
		   if(countdown.time <= 0){
			   //当倒计时结束
			   //1.显示获取验证码，
			   //2.将默认的倒计时时间置为60
			   //3.清楚定时器
			   countdown.validText = "获取验证码"
			   countdown.time = 60
			   //将flag置为false ，即读秒结束，则可以让它开始点击
			   flag = false
			   clearInterval(time)
		   }else{
			   countdown.time -= 1
			   countdown.validText =`剩余${countdown.time}s`
			   
		   }
	   },1000)
	   //表示在读秒过程中它时ture ，让它不会触发重复点击
	   flag = true
	   
	   app.globalData.utils.request({
		   url:"/get/code",
		   method:'POST',
		   data:{
			   tel:validMobile.phone		   
			   },
		  success: res => {
			  uni.showToast({
			  	title: "验证码发送成功，请尽快验证",
				icon: 'none',
				duration: 1000
			  })
		  }	,
		 fail: res => {
			 uni.showToast({
			 	title: "res.msg",
			 	icon: 'none',
			 	duration: 1000
			 })
		 }	 
	   })
	   
	   
   }
   //创建订单
	const createOrder = (orderData) => {
		console.log(orderData,"输出下入参")
		console.log(uni.getStorageSync('token'),"输出token")
		app.globalData.utils.request({
			url:"/pay/createOrder",
			method:"POST",
			header:{
				token: uni.getStorageSync('token')
			},
			data: orderData,
			success: (res) =>{
				qrcodePopup.value.open("center");
				 // 获取uQRCode实例
				  var qr = new UQRCode();
				  // 设置二维码内容
				  qr.data = res.wx_code;
				  // 设置二维码大小，必须与canvas设置的宽高一致
				  qr.size = 200;
				  // 调用制作二维码方法
				  qr.make();
				  // 获取canvas上下文
				  var canvasContext = uni.createCanvasContext('qrcode'); // 如果是组件，this必须传入
				  // 设置uQRCode实例的canvas上下文
				  qr.canvasContext = canvasContext;
				  // 调用绘制方法将二维码图案绘制到canvas上
				  qr.drawCanvas();
				
			},
			fail: (res) => {
				uni.showToast({
					title: res.data.msg,
					icon:"none",
					duration:1000
				})
			}
		})
	}
	
	//点击关闭后，跳转到订单列表
	const paymnet = () => {
		//tab跳转要用switchtab 跳转，而不能是navigateTo
		uni.switchTab({
			url:"../order/index"
		})
	}
</script>

<style>
 @import './index.css';
</style>
